package com.htudata.node.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.htudata.alarm.pojo.po.AlarmLevelPO;
import com.htudata.alarm.service.AlarmLevelService;
import com.htudata.node.dao.LinkDao;
import com.htudata.node.service.LinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class LinkServiceImpl implements LinkService {

  @Autowired
  private AlarmLevelService alarmLevelService;
  
  @Autowired
  private LinkDao linkDao;
  
  public int copyLinkToLinkTemp(String flowId) {
    return this.linkDao.insertLinkToLinkTemp(flowId);
  }
  
  public int deleteTempLinksByFlowId(String flowId) {
    return this.linkDao.deleteTempLinksByFlowId(flowId);
  }
  
  public Map<String, JSONObject> getLinkAlarmsByFlowId(String flowId) {
    JSONArray linkAlarms = this.linkDao.selectLinkAlarmsByFlowId(flowId);
    return distinctLinkAlarms(linkAlarms);
  }
  
  public Map<String, JSONObject> distinctLinkAlarms(JSONArray linkAlarms) {
    Map<String, JSONObject> linkAlarmMap = new HashMap<>();
    List<AlarmLevelPO> alarmLevelList = this.alarmLevelService.getAlarmLevelList(null);
    if (!Objects.isNull(linkAlarms))
      for (int i = 0; i < linkAlarms.size(); i++) {
        JSONObject linkAlarmObject =linkAlarms.getJSONObject(i);
        if (!linkAlarmMap.containsKey(linkAlarmObject.getString("linkId"))) {
          AlarmLevelPO alarmLevelPO = AlarmLevelService.getAlarmLevelInfo(alarmLevelList, linkAlarmObject.getInteger("level").intValue());
          linkAlarmObject.put("color", alarmLevelPO.getColor());
          linkAlarmMap.put(linkAlarmObject.getString("linkId"), linkAlarmObject);
        } else {
          JSONObject linkAlarmObject1 = linkAlarmMap.get(linkAlarmObject.getString("linkId"));
          int level1 = linkAlarmObject1.getInteger("level").intValue();
          int level = linkAlarmObject.getInteger("level").intValue();
          if (level1 < level) {
            AlarmLevelPO alarmLevelPO = AlarmLevelService.getAlarmLevelInfo(alarmLevelList, linkAlarmObject.getInteger("level").intValue());
            linkAlarmObject.put("color", alarmLevelPO.getColor());
            linkAlarmMap.put(linkAlarmObject.getString("linkId"), linkAlarmObject);
          }
        }
      }
    return linkAlarmMap;
  }
}
